package vmcs.customer;

import vmcs.common.VMCSException;
import vmcs.controller.TransactionController;
import vmcs.store.CashStore;
import vmcs.store.CashStoreItem;
import vmcs.store.Coin;
import vmcs.store.Store;
import vmcs.store.StoreController;
import vmcs.store.StoreItem;

public class ChangeGiver {

	private TransactionController transactionController;
	
	public ChangeGiver(TransactionController transactionController){
		this.transactionController = transactionController;
	}
	
	public void resetChange(){
		 transactionController.getCustomerPanel().setCollectCoinValue("0" + " C");
	}
	
	public boolean giveChange(int changeRequired) throws VMCSException{
		 int changeGiven,qty ,value,max,numOfCoins; 
         changeGiven = 0;
         Store store = transactionController.getMainController().getStoreController().getStore(Store.CASH);
         StoreItem[] storeItems = store.getItems();
         for(int i=storeItems.length -1; i >= 0; i--){
                 StoreItem storeItem = storeItems[i];
                 Coin coin = (Coin)storeItem.getContent();
                 qty = storeItem.getQuantity();
                 value = coin.getValue();
                 max = (int)Math.floor(changeRequired / value);
                 if( max > qty)
                         numOfCoins = qty;
                 else
                         numOfCoins = max;
                 
                 if (numOfCoins > 0)
					transactionController.getMainController().getMachineryController().giveChange(i, numOfCoins);
                 
                 changeGiven +=numOfCoins * value;
                 changeRequired = changeRequired - numOfCoins * value;
                 if(changeRequired == 0)
                         break;
         }
         
         transactionController.getCustomerPanel().setCollectCoinValue(String.valueOf(changeGiven) + " C");
         
         if(changeRequired>0)
                 transactionController.getCustomerPanel().setNoChangeAvailState(true);
         
         return true;
	}
	
	public void displayChangeStatus() throws VMCSException{
        boolean noChange = true;
        CashStore cashStore = (CashStore)transactionController.getMainController().getStoreController().getStore(Store.CASH);
        for(int i=0;i<=cashStore.getStoreSize()-1;i++){
                CashStoreItem cashStoreItem = (CashStoreItem)cashStore.getStoreItem(i);
                if(cashStoreItem.getQuantity()>0){
                        noChange = false;
                        break;
                }
        }
        transactionController.getCustomerPanel().setNoChangeAvailState(noChange);
}

	public TransactionController getTransactionController() {
		return transactionController;
	}

	public void setTransactionController(TransactionController transactionController) {
		this.transactionController = transactionController;
	}
	
	
	
}
